// 管理平台API服务
import apiService from './apiService.js'

class ManagementApiService {
  constructor() {
    this.baseUrl = apiService.baseUrl
  }

  // 确保API路径正确，避免重复前缀
  _ensureApiPath(path) {
    // 如果路径已经以 /api 开头，直接返回
    if (path.startsWith('/api/')) {
      return path
    }
    // 如果路径以 / 开头但不是 /api，添加 /api 前缀
    if (path.startsWith('/')) {
      return `/api${path}`
    }
    // 如果路径不以 / 开头，添加 /api/ 前缀
    return `/api/${path}`
  }

  // 项目管理API
  async getProjects(params = {}) {
    // 兼容分页参数: page(后端从0开始)/size
    let { page = 0, size = 10, project_name, name, ...rest } = params
    
    // 根据后端API，如果有项目名称，使用 /projects/search?name=xxx&page=0&size=10
    // 如果没有项目名称，使用 /projects?page=0&size=10
    const projectName = project_name || name
    
    let url
    let queryParams = { page, size }
    
    if (projectName && projectName.trim()) {
      // 使用搜索接口：GET /projects/search?name=xxx&page=0&size=10
      url = this._ensureApiPath('/projects/search')
      queryParams.name = projectName.trim()
    } else {
      // 获取所有项目：GET /projects?page=0&size=10
      url = this._ensureApiPath('/projects')
    }
    
    const res = await apiService.get(url, queryParams)
    
    // 新版接口 data.content/totalElements，老接口 data是array
    if(res && Array.isArray(res.data)) {
      return {
        ...res,
        data: {
          content: res.data,
          totalElements: res.data.length
        }
      }
    }
    return res
  }

  async getProject(id) {
    return await apiService.get(this._ensureApiPath(`/projects/${id}`))
  }

  async createProject(data) {
    return await apiService.post(this._ensureApiPath('/projects'), data)
  }

  async updateProject(id, data) {
    return await apiService.post(this._ensureApiPath(`/projects/${id}/update`), data)
  }

  async deleteProject(id) {
    return await apiService.post(this._ensureApiPath(`/projects/${id}/delete`))
  }

  // 脚本管理API
  async getScripts(params = {}) {
    let { page = 0, size = 10, ...rest } = params
    const res = await apiService.get(this._ensureApiPath('/scripts'), { ...rest, page, size })
    if(res && Array.isArray(res.data)) {
      return {
        ...res,
        data: {
          content: res.data,
          totalElements: res.data.length
        }
      }
    }
    return res
  }

  async getScript(id) {
    return await apiService.get(this._ensureApiPath(`/scripts/${id}`))
  }

  async createScript(data) {
    return await apiService.post(this._ensureApiPath('/scripts'), data)
  }

  async updateScript(id, data) {
    // 确保请求体中包含 script_id，且与路径参数一致
    const requestData = {
      ...data,
      script_id: id
    }
    return await apiService.post(this._ensureApiPath(`/scripts/${id}/update`), requestData)
  }

  // 根据脚本名称更新脚本code
  async updateScriptCodeByName(name, code) {
    if (!name || !name.trim()) {
      throw new Error('脚本名称不能为空')
    }
    
    const trimmedName = name.trim()
    console.log('开始查找脚本，名称:', trimmedName)
    
    // 先尝试加载所有脚本（不传递搜索条件，获取所有脚本）
    let scripts = null
    try {
      // 加载前100个脚本，确保能找到目标脚本
      scripts = await this.getScripts({ page: 0, size: 100 })
      console.log('查询到的脚本响应:', scripts)
    } catch (error) {
      console.error('查询脚本列表失败:', error)
      throw new Error(`查询脚本失败: ${error.message}`)
    }
    
    // 检查返回的数据结构
    const scriptList = scripts?.data?.content || scripts?.data || []
    console.log('解析后的脚本列表:', scriptList)
    console.log('脚本列表长度:', scriptList.length)
    
    // 从结果中查找匹配的脚本（精确匹配）
    const matchedScript = scriptList.find(script => {
      const scriptName = script.script_name || script.name
      const match = scriptName === trimmedName || scriptName === String(trimmedName)
      if (match) {
        console.log('找到匹配的脚本:', script)
      }
      return match
    })
    
    if (matchedScript) {
      const scriptId = matchedScript.script_id || matchedScript.id
      console.log('准备更新脚本，ID:', scriptId, '代码长度:', code?.length || 0)
      
      // 更新脚本时，根据后端API文档，需要传递 script_code 字段
      try {
        const result = await this.updateScript(scriptId, {
          script_code: code
        })
        console.log('脚本更新成功:', result)
        return result
      } catch (error) {
        console.error('更新脚本失败:', error)
        throw new Error(`更新脚本失败: ${error.message}`)
      }
    } else {
      // 如果仍然找不到，输出调试信息
      console.error('未找到匹配的脚本')
      console.error('查询到的脚本列表:', scriptList.map(s => ({
        id: s.script_id || s.id,
        name: s.script_name || s.name
      })))
      console.error('查找的脚本名称:', trimmedName)
      throw new Error(`未找到名称为 "${trimmedName}" 的脚本。查询结果: ${scriptList.length} 条记录`)
    }
  }

  async deleteScript(id) {
    return await apiService.post(this._ensureApiPath(`/scripts/${id}/delete`))
  }

  // 执行结果管理API
  async getExecutionResults(params = {}) {
    let { page = 0, size = 10, ...rest } = params
    const res = await apiService.get(this._ensureApiPath('/execution-results'), { ...rest, page, size })
    if(res && Array.isArray(res.data)) {
      return {
        ...res,
        data: {
          content: res.data,
          totalElements: res.data.length
        }
      }
    }
    return res
  }

  async getExecutionResult(id) {
    return await apiService.get(this._ensureApiPath(`/execution-results/${id}`))
  }

  async createExecutionResult(data) {
    return await apiService.post(this._ensureApiPath('/execution-results'), data)
  }

  async updateExecutionResult(id, data) {
    return await apiService.put(this._ensureApiPath(`/execution-results/${id}`), data)
  }

  async deleteExecutionResult(id) {
    return await apiService.delete(this._ensureApiPath(`/execution-results/${id}`))
  }

  // 脚本执行API
  async executeScript(scriptId, projectId) {
    return await apiService.post(this._ensureApiPath('/scripts/execute'), {
      script_id: scriptId,
      project_id: projectId
    })
  }

  async stopExecution(executionId) {
    return await apiService.post(this._ensureApiPath(`/execution-results/${executionId}/stop`))
  }

  // 批量操作API
  async batchDeleteProjects(ids) {
    return await apiService.post(this._ensureApiPath('/projects/batch-delete'), { ids })
  }

  async batchDeleteScripts(ids) {
    return await apiService.post(this._ensureApiPath('/scripts/batch-delete'), { ids })
  }

  async batchDeleteExecutionResults(ids) {
    return await apiService.post(this._ensureApiPath('/execution-results/batch-delete'), { ids })
  }

  // 统计信息API
  async getProjectStats(projectId) {
    return await apiService.get(`/projects/${projectId}/stats`)
  }

  async getScriptStats(scriptId) {
    return await apiService.get(`/scripts/${scriptId}/stats`)
  }

  async getSystemStats() {
    return await apiService.get(this._ensureApiPath('/system/stats'))
  }

  // 导出功能API
  async exportProjects(format = 'excel') {
    return await apiService.get(`/projects/export?format=${format}`, {}, {
      responseType: 'blob'
    })
  }

  async exportScripts(projectId, format = 'excel') {
    const params = projectId ? { project_id: projectId } : {}
    return await apiService.get(`/scripts/export?format=${format}`, params, {
      responseType: 'blob'
    })
  }

  async exportExecutionResults(params = {}, format = 'excel') {
    return await apiService.get(this._ensureApiPath(`/execution-results/export?format=${format}`), params, {
      responseType: 'blob'
    })
  }

  // 导入功能API
  async importProjects(file) {
    const formData = new FormData()
    formData.append('file', file)
    return await apiService.post(this._ensureApiPath('/projects/import'), formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  async importScripts(file, projectId) {
    const formData = new FormData()
    formData.append('file', file)
    if (projectId) {
      formData.append('project_id', projectId)
    }
    return await apiService.post(this._ensureApiPath('/scripts/import'), formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  // 脚本验证API
  async validateScript(code) {
    return await apiService.post(this._ensureApiPath('/scripts/validate'), { code })
  }

  async testScript(code) {
    return await apiService.post(this._ensureApiPath('/scripts/test'), { code })
  }

  // 实时监控API
  async getRunningExecutions() {
    return await apiService.get(this._ensureApiPath('/execution-results/running'))
  }

  async getExecutionLog(executionId) {
    return await apiService.get(this._ensureApiPath(`/execution-results/${executionId}/log`))
  }

  async getExecutionScreenshots(executionId) {
    return await apiService.get(this._ensureApiPath(`/execution-results/${executionId}/screenshots`))
  }

  // 定时任务API
  async getScheduledTasks(params = {}) {
    return await apiService.get(this._ensureApiPath('/scheduled-tasks'), params)
  }

  async createScheduledTask(data) {
    return await apiService.post(this._ensureApiPath('/scheduled-tasks'), data)
  }

  async updateScheduledTask(id, data) {
    return await apiService.put(`/scheduled-tasks/${id}`, data)
  }

  async deleteScheduledTask(id) {
    return await apiService.delete(`/scheduled-tasks/${id}`)
  }

  async toggleScheduledTask(id, enabled) {
    return await apiService.post(`/scheduled-tasks/${id}/toggle`, { enabled })
  }
}

// 创建单例实例
export const managementApiService = new ManagementApiService()

// 默认导出
export default managementApiService
